import { App, Config, Inject, Middleware } from '@midwayjs/decorator';
import * as _ from 'lodash';
import { RESCODE } from '@cool-midway/core';
import * as jwt from 'jsonwebtoken';
import { NextFunction, Context } from '@midwayjs/koa';
import { IMiddleware, IMidwayApplication } from '@midwayjs/core';
import { CacheManager } from '@midwayjs/cache';

/**
 * 权限校验
 */
@Middleware()
export class DoupiaopiaoAuthorityMiddleware
  implements IMiddleware<Context, NextFunction>
{
  @Config('koa.globalPrefix')
  prefix;

  @Config('module.doupiaopiao')
  doupiaopiaoConfig;

  @Inject()
  cacheManager: CacheManager;

  @App()
  app: IMidwayApplication;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      let statusCode = 200;
      let { url } = ctx;
      url = url.replace(this.prefix, '');
      const token = ctx.get('Authorization');
      const appUrl = '/app/';
      //忽略token验证的url
      const ignoreUrls = [];
      // 路由地址为 app前缀的 需要权限校验
      if (_.startsWith(url, appUrl)) {
        try {
          ctx.app_userinfo = jwt.verify(token, this.doupiaopiaoConfig.jwt.secret);
        } catch (err) { }
        // 不需要登录 无需权限校验
        if (
          new RegExp(`^${appUrl}?.*/open/`).test(url) ||
          ignoreUrls.includes(url)
        ) {
          await next();
          return;
        }
        if (ctx.app_userinfo) {
          // const rToken = await this.cacheManager.get(
          //   `${this.doupiaopiaoConfig.name}:token:${ctx.app_userinfo.userId}`
          // );
          // 要登录每个人都有权限的接口
          if (new RegExp(`^${appUrl}?.*/comm/`).test(url)) {
            await next();
            return;
          }
          // 如果传的token是refreshToken则校验失败
          if (ctx.app_userinfo.isRefresh) {
            ctx.status = 401;
            ctx.body = {
              code: RESCODE.COMMFAIL,
              message: '(1)登录失效~',
            };
            return;
          }
          // 判断密码版本是否正确
          const passwordV = await this.cacheManager.get(
            `${this.doupiaopiaoConfig.name}:passwordVersion:${ctx.app_userinfo.userId}`
          );
          if (passwordV != ctx.app_userinfo.passwordVersion) {
            ctx.status = 401;
            ctx.body = {
              code: RESCODE.COMMFAIL,
              message: '(2)登录失效~',
            };
            return;
          }

          // if (!rToken) {
          //   ctx.status = 401;
          //   ctx.body = {
          //     code: RESCODE.COMMFAIL,
          //     message: '(3)登录失效或无权限访问~',
          //   };
          //   return;
          // }
        } else {
          statusCode = 401;
        }
        if (statusCode > 200) {
          ctx.status = statusCode;
          ctx.body = {
            code: RESCODE.COMMFAIL,
            message: '(4)登录失效或无权限访问~',
          };
          return;
        }
      }
      await next();
    };
  }
}
